﻿using Testudo.Core;
using Testudo.Models;
using Testudo.Services;

namespace Testudo.WebApp.Services;

internal class WcsProxyService : IWcsProxyService
{
    public IScenarioProxy Scenario { get; }
    public event EventHandler<ScenarioConfig> ScenarioChanged;
    //public event Action<(Guid, ScenarioStatus)>
    public WcsProxyService(IServiceProvider provider)
    {
        var scopedProvider = provider.CreateScope().ServiceProvider;
        Repository = provider.CreateScope().ServiceProvider.GetService<IRepository<ScenarioConfig>>();
        Scenario = scopedProvider.GetService<IScenarioProxy>();
    }

    private IRepository<ScenarioConfig> Repository { get; }

    public async Task LoadScenario(Guid id)
    {
        if (Scenario.Id != id)
        {
            await Scenario.Unload();
        }

        var config = await Repository.GetAsync(id);
        if (config != null)
        {
            //Scenario = new ScenarioProxy();
            await Scenario.Load(config);
            ScenarioChanged?.Invoke(this, config);
        }
    }

    public async Task UnloadScenario(Guid id)
    {
        if (Scenario.Id == id)
        {
            await Scenario.Stop();
            await Scenario.Unload();
            //Scenario = null;
            ScenarioChanged?.Invoke(this, null);
        }
    }

    public async Task Start(Guid id)
    {
        if (Scenario.Id == id)
        {
            await Scenario.Start();
        }
    }

    public async Task Stop(Guid id)
    {
        if (Scenario.Id == id)
        {
            await Scenario.Stop();
        }
    }


}